package org.example.code.test2024.ten_mouth;

import java.util.Arrays;

public class test1024 {
    public static void main(String[] args) {
        int[] num = {8,9,2,7};
        balanceArray(num);
//        System.out.println(sum);
    }

    private static int countInversions(int[] num) {
        int left = 0, right = num.length - 1;
        int[] temp = new int[num.length];
        return countSum(num,temp,left,right);
    }

    private static int countSum(int[] num, int[] temp, int left, int right) {
        if(left>=right){
            return 0;
        }
        int mid = left + (right - left) / 2;
        int count = countSum(num,temp,left,mid);
        count=count+countSum(num,temp,mid+1,right);
        count=count+countNum(num,temp,left,mid,right);
        return count;
    }

    private static int countNum(int[] num, int[] temp, int left, int mid,int right) {
        int i=left,j=mid+1;
        int k=0,count=0;
        while(i<=mid&&j<=right){
            if(num[i]<num[j]){
                temp[k++]=num[i++];
            }else{
                temp[k++]=num[j++];
                count = count+(mid-i+1);
            }
        }
        while(i<=mid){
            temp[k++]=num[i++];
        }
        while(j<=right){
            temp[k++]=num[j++];
        }
        for(int p=left;p<=right;p++){
            num[p]=temp[p];
        }
        return count;
    }


    public static void balanceArray(int[] arr) {
        int moves = 0;
        int n = arr.length;

        while (!isBalanced(arr)) {
            for (int i = 0; i < n - 1; i++) {
                if (arr[i] < arr[i + 1]) {
                    arr[i]++;
                    arr[i + 1]--;
                    moves++;
                    printArray(arr, moves);
                }
                else if (arr[i] > arr[i + 1]) {
                    arr[i]--;
                    arr[i + 1]++;
                    moves++;
                    printArray(arr, moves);
                }
            }
        }

        System.out.println("Total moves: " + moves);
    }

    private static boolean isBalanced(int[] arr) {
        int total = Arrays.stream(arr).sum();
        int remainder = total % arr.length;
        int first = arr[0];
        for (int i = 1; i < arr.length; i++) {
            if (arr[i] != first&&Math.abs(first-arr[i])>remainder) {
                return false;
            }
        }
        return true;
    }

    private static void printArray(int[] arr, int step) {
        System.out.println("Step " + step + ": " + Arrays.toString(arr));
    }
}
